# 自定义登录认证类
import jwt
from rest_framework.authentication import BaseAuthentication
from rest_framework.exceptions import AuthenticationFailed
from dj_mall import settings
from manage.models.system import User
from manage.serializers.system import UserSerializer


# 必须继承BaseAuthentication基础类
class JWTAuth(BaseAuthentication):
    # 重写authenticate方法
    def authenticate(self, request):
        # 接收请求头Authorization
        auth_header=request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            raise AuthenticationFailed('没有检测登录凭证token')
        # 从请求头中解析登录凭证token
        token=auth_header.split(' ')[1]
        try:
            payload=jwt.decode(token,settings.SECRET_KEY,algorithms='HS256')
        except jwt.DecodeError:
            raise AuthenticationFailed('登录凭证token解析失败')
        except jwt.ExpiredSignatureError:
            raise AuthenticationFailed('登录凭证token已过期')
        except jwt.InvalidTokenError:
            raise AuthenticationFailed('非法登录凭证token')
        # 从payload中获取用户数据
        user_id=payload.get('user_id')
        # 根据用户user_id查询用户数据
        try:
            queryset=User.objects.get(id=user_id)
            user=UserSerializer(queryset).data
        except User.DoesNotExist:
            raise AuthenticationFailed('用户信息不存在')
        # 返回用户对象和登录凭证token
        return user,token

